layui.use(['table','form', 'element'], function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        element = layui.element;
    //方法级渲染
    table.render({
        elem: '#job'
        , url: '/monitor/job/list'
        , toolbar: '#toolbarTable'
        , title: '定时任务'
        , totalRow: true
        ,skin: 'line'
        , id: "job"
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'jobId', title: '任务id', width: 100, sort: true, align: 'center'}
            , {field: 'jobName', title: '任务名称', width: 300, sort: true}
            , {field: 'invokeTarget', title: '调用目标字符串', width: 500, sort: true}
            , {field: 'cronExpression', title: 'cron表达式', width: 200, sort: true}
            , {field:'status', title:'状态', width:200, templet: '#switchStatus', unresize: true}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 300}
        ]]
        , even: true
        , page: true //是否显示分页
        , skip: true //开启跳页
        , limits: [10, 30, 60]
        , width: 1700
        // , height: 'full-150'
        , limit: 10 //每页默认显示的数量
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data.records //解析数据列表
            };
        }
        ,done:function (res,currentCount) {
            //***重点***：table渲染完成后渲染element进度条
            element.render()
        }

    });

    //监听性别操作
    form.on('switch(statusFilter)', function(obj){
        // layer.tips(this.value + ' ' + this.name + '：'+ obj.elem.checked, obj.othis);
        const params = {
            jobId: this.value,
            status: obj.elem.checked ? 0 : 1
        };
        $.ajax({
            url: '/monitor/job/changeStatus',
            data: JSON.stringify(params),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            type: "PUT",
            success: function (result) {
                layer.msg(result.desc, {icon: 1, time: 3000}, function () {

                })
            }
        })
    });
    //头工具栏事件
    table.on('toolbar(job)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        switch (obj.event) {
            case 'add':
                add();
                break;
            case 'del':
                if (data.length==0){
                    layer.msg("请先勾选数据",{icon:2,time:3000});
                    return;
                }
                let ids = "";
                for (let i = 0; i < data.length; i++) {
                    ids+=data[i].id+","
                }
                ids = ids.substr(0,ids.length-1);
                del(ids);
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(job)', function (obj) {
        const data = obj.data;
        if (obj.event === 'update'){
            update(data);
        }else if (obj.event === 'del'){
            del(data.jobId)
        }else if (obj.event === 'info'){
            info(data)
        }else if (obj.event === 'run'){
            run(data)
        }
    });
    function run(data) {
        $.ajax({
            type: "put",//方法类型
            data: JSON.stringify(data),
            dataType: "json",//预期服务器返回的数据类型
            url: "/monitor/job/run",//url
            contentType: "application/json;charset=utf-8",
            success: function (result) {
                if (result.code == 0) {
                    layer.msg(result.desc,{icon:1,time:1000},function () {
                    });
                }else {
                    layer.msg(result.desc,{icon:2,time:3000},function () {
                    });
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    function del(ids) {
        layer.confirm("确认要删除吗，删除后不能恢复", { title: "删除确认" }, function (index) {
            $.ajax({
                type: "delete",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/monitor/job/"+ids,//url
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg(result.data,{icon:1,time:1000},function () {
                            location.reload();
                        });
                    };
                },
                error: function () {
                    alert("异常！");
                }
            });
        })
    }

    function add() {
        layer.open({
            type: 2,
            title: '新增任务',
            area: ['900px', '600px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["add.html", 'no'],
            success: function (layero, index) {
                form.render();
            },
            yes: function () {
            }
        });
    }

    function update(data) {
        layer.open({
            type: 2,
            title: '修改任务',
            area: ['900px', '600px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["update.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find("#jobId").val(data.jobId);
                body.find("#jobName").val(data.jobName);
                body.find("#invokeTarget").val(data.invokeTarget);
                body.find("#cronExpression").val(data.cronExpression);
                body.find("#status").val(data.status);
                body.find("#remark").val(data.remark);
            },
            yes: function () {
            }
        });
    }

    function info(data) {
        $.ajax({
            url: '/monitor/job/'+data.jobId,
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            type: "get",
            success: function (result) {
                if (result.code=200){
                    const data= result.data
                    layer.open({
                        type: 2,
                        title: '任务详情',
                        area: ['700px', '400px'],
                        fix: false, //
                        closeBtn: false,
                        shift: 2,
                        shadeClose: true,
                        content: ["info.html", 'no'],
                        success: function (layero, index) {
                            const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                            body.find("#jobId").val(data.jobId);
                            body.find("#jobId").html(data.jobId);
                            body.find("#jobName").html(data.jobName);
                            body.find("#cronExpression").html(data.cronExpression);
                            body.find("#invokeTarget").html(data.invokeTarget);
                            body.find("#nextValidTime").html(data.nextValidTime);
                            body.find("#createTime").html(data.createTime);
                            body.find("#status").html(data.status==0?"正常":"暂停");
                        },
                        yes: function () {
                        }
                    });
                }
            }
        })

    }

    $('#query').click(function(){
        search();
    });
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            search();
        }
    });
    function search(){
        const content = $('#content');
        //执行重载
        table.reloadData('job', {
            method: 'get',
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                content: content.val(),
            }
        }, 'data');
    }
});